package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    public static final String WX_LOGIN_URL="https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 微信登录
     * ①请求wx服务器获取用户的open_id
     * ②若为空则抛出异常
     * ③若不为空则判断是否在表中存在
     * ④不存在则新增，存在则返回
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //请求微信服务器获取openid
        String openId=getOpenId(userLoginDTO.getCode());
        //openId不存在
        if(openId==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user=userMapper.selectByOpenId(openId);
        //用户不存在
        if(user==null){
            user=User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    /**
     * 请求微信服务器获取oppenid
     * @param code
     * @return
     */
    private String getOpenId(String code){
        Map<String,String>map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String result=HttpClientUtil.doGet(WX_LOGIN_URL,map);
        JSONObject jsonObject= JSONObject.parseObject(result);
        return jsonObject.getString("openid");
    }
}
